#include "ChartWidget.h"
#include <QChart>
#include <QLineSeries>
#include <QScatterSeries>
#include <QChartView>
#include <QValueAxis>
#include <QHeaderView>
#include <QDebug>
#include <QFontMetrics>
#include <QLinearGradient>
#include <QBrush>
#include <QPen>
#include <cmath>
#include <limits>
#include <algorithm>

ChartWidget::ChartWidget(QWidget *parent)
    : QFrame(parent)
    , m_xMin(0), m_xMax(20)
    , m_yMin(500), m_yMax(2500)
    , m_currentTime(2.0)
    , m_autoRangeEnabled(true)  // 默认启用自动范围调整
    , m_xPadding(0.1)  // 默认10%边距
    , m_yPadding(0.1)  // 默认10%边距
{
    setupUI();
    setupConnections();
    setupChart();
    setupTestData();
}

ChartWidget::~ChartWidget()
{
    if (m_updateTimer) {
        m_updateTimer->stop();
        delete m_updateTimer;
    }
}

void ChartWidget::setupUI()
{
    setStyleSheet("ChartWidget{ border: 2px solid #003C6D; border-radius: 8px;}");

    m_mainLayout = new QVBoxLayout(this);
    m_mainLayout->setContentsMargins(6, 6, 6, 6);
    m_mainLayout->setSpacing(6);

    // 创建图例图标区域
    QWidget *iconWt = createLegendWidget();
    m_mainLayout->addWidget(iconWt, 1);
    
    // 图表视图
    m_chartView = new QChartView();
    m_chartView->setObjectName("chartArea");
    
    // 数据表格
    QHBoxLayout *dataTableLayout = new QHBoxLayout();
    dataTableLayout->setContentsMargins(0, 0, 0, 0);
    dataTableLayout->setSpacing(0);
    QLabel *headerWt = new QLabel(QString("枪位"));
    headerWt->setStyleSheet("background-color: #0A2E5B; border: 2px solid #05417B; font-size: 16px; font-weight: medium; color: #FFFFFF;"
        "border-top-left-radius: 4px; border-bottom-left-radius: 4px; border-top-right-radius: 0px; border-bottom-right-radius: 0px;");
    headerWt->setFixedWidth(52);
    headerWt->setAlignment(Qt::AlignCenter);
    dataTableLayout->addWidget(headerWt);
    m_dataTable = new QTableWidget(2, 7);
    m_dataTable->setObjectName("chartDataTable");
    m_dataTable->horizontalHeader()->setVisible(false);
    m_dataTable->verticalHeader()->setVisible(false);
    m_dataTable->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_dataTable->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    m_dataTable->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    m_dataTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_dataTable->setSelectionMode(QAbstractItemView::NoSelection);
    m_dataTable->setFocusPolicy(Qt::NoFocus);
    // 使用全局样式表 #chartDataTable
    m_dataTable->setStyleSheet(R"(QTableWidget {
        border-top: 2px solid #05417B;
        border-bottom: 2px solid #05417B;
        border-left: none;
        border-right: 2px solid #05417B;
        border-top-right-radius: 4px;
        border-bottom-right-radius: 4px;
        border-bottom-left-radius: 0px;
        border-top-left-radius: 0px;
    })");
    m_dataTable->setShowGrid(true);
    m_dataTable->setGridStyle(Qt::SolidLine);
    m_dataTable->setAttribute(Qt::WA_StyledBackground, true);
    dataTableLayout->addWidget(m_dataTable);

    QFrame *chartWt = new QFrame();
    chartWt->setStyleSheet("QFrame{background-color: #051D3E; border: none; border-radius: 4px;}");
    QVBoxLayout *chartLayout = new QVBoxLayout(chartWt);
    chartLayout->setContentsMargins(2, 2, 2, 2);
    chartLayout->setSpacing(2);
    chartLayout->addWidget(m_chartView, 7);
    chartLayout->addLayout(dataTableLayout, 2);
    m_mainLayout->addWidget(chartWt, 9);
}

void ChartWidget::setupConnections()
{
    // 设置定时器用于动画效果
    m_updateTimer = new QTimer(this);
    m_updateTimer->setInterval(100);
    connect(m_updateTimer, &QTimer::timeout, this, [this]() {
        update();
    });
}

void ChartWidget::setupChart()
{
    // 创建图表
    m_chart = new QChart();
    m_chart->setBackgroundBrush(QBrush(QColor("#08254D")));
    m_chart->setPlotAreaBackgroundBrush(QBrush(QColor("#021D43")));
    m_chart->setPlotAreaBackgroundVisible(true);
    
    // 创建坐标轴
    m_xAxis = new QValueAxis();
    m_xAxis->setRange(m_xMin, m_xMax);
    m_xAxis->setTickCount(11); // 0,2,4,6,8,10,12,14,16,18,20 (11个刻度)
    m_xAxis->setTickInterval(2); // 每个刻度间隔2
    m_xAxis->setTitleText("");
    m_xAxis->setTitleBrush(QBrush(QColor("#FFFFFF")));
    m_xAxis->setLabelsBrush(QBrush(QColor("#FFFFFF")));
    // 设置X轴字体
    QFont xAxisFont("Microsoft YaHei", 6, QFont::Normal);
    m_xAxis->setLabelsFont(xAxisFont);
    m_xAxis->setTitleFont(xAxisFont);
    // 设置网格线为虚线
    QPen xGridPen(QColor("#1F3D60"));
    xGridPen.setStyle(Qt::DashLine);
    m_xAxis->setGridLinePen(xGridPen);
    m_xAxis->setLinePenColor(QColor("#3E70A7"));
    
    m_yAxis = new QValueAxis();
    m_yAxis->setRange(m_yMin, m_yMax);
    m_yAxis->setTickCount(5); // 500,1000,1500,2000,2500 (5个刻度)
    m_yAxis->setTickInterval(500); // 每个刻度间隔500
    m_yAxis->setTitleText("");
    m_yAxis->setTitleBrush(QBrush(QColor("#FFFFFF")));
    m_yAxis->setLabelsBrush(QBrush(QColor("#FFFFFF")));
    // 设置Y轴字体
    QFont yAxisFont("Microsoft YaHei", 6, QFont::Normal);
    m_yAxis->setLabelsFont(yAxisFont);
    m_yAxis->setTitleFont(yAxisFont);
    // 设置网格线为虚线
    QPen yGridPen(QColor("#1F3D60"));
    yGridPen.setStyle(Qt::DashLine);
    m_yAxis->setGridLinePen(yGridPen);
    m_yAxis->setLinePenColor(QColor("#3E70A7"));
    
    // 创建数据系列
    m_actualLanceSeries = new QLineSeries();
    m_actualLanceSeries->setName("实际枪位");
    m_actualLanceSeries->setPen(QPen(QColor("#FF0000"), 2));
    
    m_standardLanceSeries = new QLineSeries();
    m_standardLanceSeries->setName("标准枪位");
    m_standardLanceSeries->setPen(QPen(QColor("#800080"), 2));
    
    m_oxygenFlowSeries = new QLineSeries();
    m_oxygenFlowSeries->setName("氧气流量");
    m_oxygenFlowSeries->setPen(QPen(QColor("#FFFF00"), 2));
    
    m_limeClassSeries = new QScatterSeries();
    m_limeClassSeries->setName("石灰类");
    m_limeClassSeries->setMarkerShape(QScatterSeries::MarkerShapeRectangle);
    m_limeClassSeries->setColor(QColor("#FFFFFF"));
    m_limeClassSeries->setMarkerSize(10);
    
    m_rawWhiteClassSeries = new QScatterSeries();
    m_rawWhiteClassSeries->setName("生白类");
    m_rawWhiteClassSeries->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    m_rawWhiteClassSeries->setColor(QColor("#FFFFFF"));
    m_rawWhiteClassSeries->setMarkerSize(10);
    
    m_ironOreClassSeries = new QScatterSeries();
    m_ironOreClassSeries->setName("铁矿石类");
    m_ironOreClassSeries->setMarkerShape(QScatterSeries::MarkerShapeCircle);
    m_ironOreClassSeries->setColor(QColor("#FFFFFF"));
    m_ironOreClassSeries->setMarkerSize(10);
    
    // 添加系列到图表
    m_chart->addSeries(m_actualLanceSeries);
    m_chart->addSeries(m_standardLanceSeries);
    m_chart->addSeries(m_oxygenFlowSeries);
    m_chart->addSeries(m_limeClassSeries);
    m_chart->addSeries(m_rawWhiteClassSeries);
    m_chart->addSeries(m_ironOreClassSeries);
    
    // 设置坐标轴
    m_chart->addAxis(m_xAxis, Qt::AlignBottom);
    m_chart->addAxis(m_yAxis, Qt::AlignLeft);
    
    // 附加系列到坐标轴
    m_actualLanceSeries->attachAxis(m_xAxis);
    m_actualLanceSeries->attachAxis(m_yAxis);
    m_standardLanceSeries->attachAxis(m_xAxis);
    m_standardLanceSeries->attachAxis(m_yAxis);
    m_oxygenFlowSeries->attachAxis(m_xAxis);
    m_oxygenFlowSeries->attachAxis(m_yAxis);
    m_limeClassSeries->attachAxis(m_xAxis);
    m_limeClassSeries->attachAxis(m_yAxis);
    m_rawWhiteClassSeries->attachAxis(m_xAxis);
    m_rawWhiteClassSeries->attachAxis(m_yAxis);
    m_ironOreClassSeries->attachAxis(m_xAxis);
    m_ironOreClassSeries->attachAxis(m_yAxis);
    
    // 设置图例 - 隐藏图例
    m_chart->legend()->setVisible(false);
    
    // 设置图表边距 - 尽可能贴边
    m_chart->setMargins(QMargins(0, 0, 0, 0));
    m_chart->setContentsMargins(0, 0, 0, 0);
    
    m_chartView->setChart(m_chart);
    m_chartView->setRenderHint(QPainter::Antialiasing);
    m_chartView->setContentsMargins(0, 0, 0, 0);
}

void ChartWidget::setupTestData()
{
    // 设置信息框内容
    m_duration = "5'30\"";
    m_height = "1400/1450";
    m_flowRate = "28636";
    
    // 添加实际枪位数据（红色线）
    QList<QPointF> actualLanceData = {
        {0, 2000}, {1, 1500}, {2, 1500}, {3, 1200}, {4, 1200}, {5, 1100}, {6, 1100}, {7, 1100}
    };
    setDataSeries(ActualLancePos, actualLanceData);
    
    // 添加标准枪位数据（紫色线）
    QList<QPointF> standardLanceData = {
        {0, 1500}, {1, 1500}, {2, 1500}, {3, 1200}, {4, 1200}, {5, 1100}, {6, 1100}, {7, 1100}
    };
    setDataSeries(StandardLancePos, standardLanceData);
    
    // 添加氧气流量数据（黄色线）
    QList<QPointF> oxygenFlowData = {
        {0, 1600}, {1, 2100}, {2, 2200}, {3, 2000}, {4, 2300}, {5, 2100}, {6, 2200}, {7, 2000}
    };
    setDataSeries(OxygenFlow, oxygenFlowData);
    
    // 添加散点数据
    addDataPoint(LimeClass, 3.5, 1100);      // 石灰类（白色菱形）
    addDataPoint(RawWhiteClass, 4.5, 900);   // 生白类（白色方形）
    addDataPoint(IronOreClass, 6.0, 900);    // 铁矿石类（白色圆形）
}

void ChartWidget::addDataPoint(DataSeriesType type, double x, double y)
{
    switch (type) {
        case LimeClass:
            m_limeClassSeries->clear();
            m_limeClassSeries->append(x, y);
            break;
        case RawWhiteClass:
            m_rawWhiteClassSeries->clear();
            m_rawWhiteClassSeries->append(x, y);
            break;
        case IronOreClass:
            m_ironOreClassSeries->clear();
            m_ironOreClassSeries->append(x, y);
            break;
        case ActualLancePos:
            m_actualLanceSeries->append(x, y);
            break;
        case StandardLancePos:
            m_standardLanceSeries->append(x, y);
            break;
        case OxygenFlow:
            m_oxygenFlowSeries->append(x, y);
            break;
    }
    
    // 如果启用了自动范围调整，更新范围
    if (m_autoRangeEnabled) {
        updateRangeFromData();
    }
}

void ChartWidget::setDataSeries(DataSeriesType type, const QList<QPointF> &points)
{
    QLineSeries *series = nullptr;
    QScatterSeries *scatterSeries = nullptr;
    
    switch (type) {
        case ActualLancePos:
            series = m_actualLanceSeries;
            break;
        case StandardLancePos:
            series = m_standardLanceSeries;
            break;
        case OxygenFlow:
            series = m_oxygenFlowSeries;
            break;
        case LimeClass:
            scatterSeries = m_limeClassSeries;
            break;
        case RawWhiteClass:
            scatterSeries = m_rawWhiteClassSeries;
            break;
        case IronOreClass:
            scatterSeries = m_ironOreClassSeries;
            break;
    }
    
    if (series) {
        series->clear();
        for (const QPointF &point : points) {
            series->append(point.x(), point.y());
        }
    } else if (scatterSeries) {
        scatterSeries->clear();
        if (!points.isEmpty()) {
            const QPointF &point = points.last();
            scatterSeries->append(point.x(), point.y());
        }
    }
    
    // 如果启用了自动范围调整，更新范围
    if (m_autoRangeEnabled) {
        updateRangeFromData();
    }
}

void ChartWidget::setXRange(double min, double max)
{
    // 确保最小值不小于0
    if (min < 0.0) {
        min = 0.0;
    }
    m_xMin = min;
    m_xMax = max;
    if (m_xAxis) {
        m_xAxis->setRange(min, max);
    }
}

void ChartWidget::setYRange(double min, double max)
{
    // 确保最小值不小于0
    if (min < 0.0) {
        min = 0.0;
    }
    m_yMin = min;
    m_yMax = max;
    if (m_yAxis) {
        m_yAxis->setRange(min, max);
    }
}

void ChartWidget::setAutoRangeEnabled(bool enabled)
{
    m_autoRangeEnabled = enabled;
    if (enabled) {
        updateRangeFromData();
    }
}

bool ChartWidget::isAutoRangeEnabled() const
{
    return m_autoRangeEnabled;
}

void ChartWidget::updateRangeFromData()
{
    if (!m_chart || !m_xAxis || !m_yAxis) {
        return;
    }
    
    double xMin = std::numeric_limits<double>::max();
    double xMax = std::numeric_limits<double>::lowest();
    double yMin = std::numeric_limits<double>::max();
    double yMax = std::numeric_limits<double>::lowest();
    
    bool hasData = false;
    
    // 检查线系列的数据范围
    auto checkLineSeries = [&](QLineSeries *series) {
        if (!series) return;
        
        for (const QPointF &point : series->points()) {
            if (!qIsNaN(point.x()) && !qIsInf(point.x()) &&
                !qIsNaN(point.y()) && !qIsInf(point.y())) {
                xMin = std::min(xMin, point.x());
                xMax = std::max(xMax, point.x());
                yMin = std::min(yMin, point.y());
                yMax = std::max(yMax, point.y());
                hasData = true;
            }
        }
    };
    
    // 检查散点系列的数据范围
    auto checkScatterSeries = [&](QScatterSeries *series) {
        if (!series) return;
        
        for (const QPointF &point : series->points()) {
            if (!qIsNaN(point.x()) && !qIsInf(point.x()) &&
                !qIsNaN(point.y()) && !qIsInf(point.y())) {
                xMin = std::min(xMin, point.x());
                xMax = std::max(xMax, point.x());
                yMin = std::min(yMin, point.y());
                yMax = std::max(yMax, point.y());
                hasData = true;
            }
        }
    };
    
    // 检查所有线系列
    checkLineSeries(m_actualLanceSeries);
    checkLineSeries(m_standardLanceSeries);
    checkLineSeries(m_oxygenFlowSeries);
    
    // 检查所有散点系列
    checkScatterSeries(m_limeClassSeries);
    checkScatterSeries(m_rawWhiteClassSeries);
    checkScatterSeries(m_ironOreClassSeries);
    
    // 如果没有数据，保持当前范围
    if (!hasData) {
        return;
    }
    
    // 计算边距
    double xRange = xMax - xMin;
    double yRange = yMax - yMin;
    
    // 如果范围太小，设置最小范围
    if (xRange < 1e-10) {
        xRange = 1.0;
        xMin -= 0.5;
        xMax += 0.5;
    }
    if (yRange < 1e-10) {
        yRange = 1.0;
        yMin -= 0.5;
        yMax += 0.5;
    }
    
    // 应用边距
    double xPadding = xRange * m_xPadding;
    double yPadding = yRange * m_yPadding;
    
    double newXMin = xMin - xPadding;
    double newXMax = xMax + xPadding;
    double newYMin = yMin - yPadding;
    double newYMax = yMax + yPadding;
    
    // 确保最小值不小于0
    if (newXMin < 0.0) {
        newXMin = 0.0;
    }
    if (newYMin < 0.0) {
        newYMin = 0.0;
    }
    
    // 更新范围
    m_xMin = newXMin;
    m_xMax = newXMax;
    m_yMin = newYMin;
    m_yMax = newYMax;
    
    // 更新坐标轴
    m_xAxis->setRange(newXMin, newXMax);
    m_yAxis->setRange(newYMin, newYMax);
    
    // 更新刻度间隔（保持合理的刻度数量）
    double xTickInterval = (newXMax - newXMin) / 10.0;
    double yTickInterval = (newYMax - newYMin) / 5.0;
    
    // 将刻度间隔调整为合适的值
    if (xTickInterval > 0) {
        double xTickPower = std::pow(10.0, std::floor(std::log10(xTickInterval)));
        xTickInterval = std::ceil(xTickInterval / xTickPower) * xTickPower;
        m_xAxis->setTickInterval(xTickInterval);
    }
    
    if (yTickInterval > 0) {
        double yTickPower = std::pow(10.0, std::floor(std::log10(yTickInterval)));
        yTickInterval = std::ceil(yTickInterval / yTickPower) * yTickPower;
        m_yAxis->setTickInterval(yTickInterval);
    }
}

void ChartWidget::setTableItem(int row, int column, const QString& value)
{
    if (!m_dataTable) {
        return;
    }
    if (row < 0 || row >= m_dataTable->rowCount() || column < 0 || column >= m_dataTable->columnCount()) {
        return;
    }

    QTableWidgetItem* item = m_dataTable->item(row, column);
    if (!item) {
        item = new QTableWidgetItem();
        item->setTextAlignment(Qt::AlignCenter);
        m_dataTable->setItem(row, column, item);
    }
    item->setText(value);
}

QString ChartWidget::tableItem(int row, int column) const
{
    if (!m_dataTable) {
        return QString();
    }
    if (row < 0 || row >= m_dataTable->rowCount() || column < 0 || column >= m_dataTable->columnCount()) {
        return QString();
    }

    QTableWidgetItem* item = m_dataTable->item(row, column);
    return item ? item->text() : QString();
}

void ChartWidget::setCurrentTime(double time)
{
    m_currentTime = time;
    // 这里可以添加当前时间线的绘制逻辑
}

void ChartWidget::setInfoBox(const QString &duration, const QString &height, const QString &flowRate)
{
    m_duration = duration;
    m_height = height;
    m_flowRate = flowRate;
    // 这里可以添加信息框的显示逻辑
}

void ChartWidget::resizeEvent(QResizeEvent *event)
{
    QWidget::resizeEvent(event);
    update();
}
QWidget* ChartWidget::createLegendWidget()
{
    QWidget *iconWt = new QWidget();
    iconWt->setStyleSheet("background-color: transparent;");
    
    QHBoxLayout *iconLayout = new QHBoxLayout(iconWt);
    iconLayout->setContentsMargins(10, 0, 10, 0);
    iconLayout->setSpacing(24);

    iconLayout->addStretch();
    
    // 石灰类 - 菱形
    QHBoxLayout *limeLayout = new QHBoxLayout();
    limeLayout->setContentsMargins(0, 0, 0, 0);
    limeLayout->setSpacing(2);
    QLabel *limeIcon = new QLabel("◆");
    limeIcon->setStyleSheet("color: #CCCCCC; font-size: 14px; background-color: transparent;");
    QLabel *limeLabel = new QLabel("石灰类");
    limeLabel->setStyleSheet("color: #FFFFFF; font-size: 12px; background-color: transparent;");
    limeLayout->addWidget(limeIcon);
    limeLayout->addWidget(limeLabel);
    iconLayout->addLayout(limeLayout);
    
    // 生白类 - 方形
    QHBoxLayout *rawWhiteLayout = new QHBoxLayout();
    rawWhiteLayout->setContentsMargins(0, 0, 0, 0);
    rawWhiteLayout->setSpacing(2);
    QLabel *rawWhiteIcon = new QLabel("■");
    rawWhiteIcon->setStyleSheet("color: #CCCCCC; font-size: 14px; background-color: transparent;");
    QLabel *rawWhiteLabel = new QLabel("生白类");
    rawWhiteLabel->setStyleSheet("color: #FFFFFF; font-size: 12px; background-color: transparent;");
    rawWhiteLayout->addWidget(rawWhiteIcon);
    rawWhiteLayout->addWidget(rawWhiteLabel);
    iconLayout->addLayout(rawWhiteLayout);

    // 铁矿石类 - 圆形
    QHBoxLayout *ironOreLayout = new QHBoxLayout();
    ironOreLayout->setContentsMargins(0, 0, 0, 0);
    ironOreLayout->setSpacing(2);
    QLabel *ironOreIcon = new QLabel("●");
    ironOreIcon->setStyleSheet("color: #CCCCCC; font-size: 14px; background-color: transparent;");
    QLabel *ironOreLabel = new QLabel("铁矿石类");
    ironOreLabel->setStyleSheet("color: #FFFFFF; font-size: 12px; background-color: transparent;");
    ironOreLayout->addWidget(ironOreIcon);
    ironOreLayout->addWidget(ironOreLabel);
    iconLayout->addLayout(ironOreLayout);

    // 实际枪位 - 红色线
    QHBoxLayout *actualLanceLayout = new QHBoxLayout();
    actualLanceLayout->setContentsMargins(0, 0, 0, 0);
    actualLanceLayout->setSpacing(2);
    QLabel *actualLanceIcon = new QLabel("—");
    actualLanceIcon->setStyleSheet("color: #FF0000; font-size: 16px; font-weight: bold; background-color: transparent;");
    QLabel *actualLanceLabel = new QLabel("实际枪位");
    actualLanceLabel->setStyleSheet("color: #FFFFFF; font-size: 12px; background-color: transparent;");
    actualLanceLayout->addWidget(actualLanceIcon);
    actualLanceLayout->addWidget(actualLanceLabel);
    iconLayout->addLayout(actualLanceLayout);

    // 标准枪位 - 紫色线
    QHBoxLayout *standardLanceLayout = new QHBoxLayout();
    standardLanceLayout->setContentsMargins(0, 0, 0, 0);
    standardLanceLayout->setSpacing(2);
    QLabel *standardLanceIcon = new QLabel("—");
    standardLanceIcon->setStyleSheet("color: #800080; font-size: 16px; font-weight: bold; background-color: transparent;");
    QLabel *standardLanceLabel = new QLabel("标准枪位");
    standardLanceLabel->setStyleSheet("color: #FFFFFF; font-size: 12px; background-color: transparent;");
    standardLanceLayout->addWidget(standardLanceIcon);
    standardLanceLayout->addWidget(standardLanceLabel);
    iconLayout->addLayout(standardLanceLayout);

    // 氧气流量 - 黄色线
    QHBoxLayout *oxygenFlowLayout = new QHBoxLayout();
    oxygenFlowLayout->setContentsMargins(0, 0, 0, 0);
    oxygenFlowLayout->setSpacing(2);
    QLabel *oxygenFlowIcon = new QLabel("—");
    oxygenFlowIcon->setStyleSheet("color: #FFFF00; font-size: 16px; font-weight: bold; background-color: transparent;");
    QLabel *oxygenFlowLabel = new QLabel("氧气流量");
    oxygenFlowLabel->setStyleSheet("color: #FFFFFF; font-size: 12px; background-color: transparent;");
    oxygenFlowLayout->addWidget(oxygenFlowIcon);
    oxygenFlowLayout->addWidget(oxygenFlowLabel);
    iconLayout->addLayout(oxygenFlowLayout);

    iconLayout->addStretch();
    
    return iconWt;
}

